<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>无限盲盒信息</span>
      </div>
      <!-- 图表 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" v-loading="formLoading">
        <el-form-item label="盲盒名称" prop="name">
          <el-input v-model="form.name" style="width:360px" placeholder="请输入盲盒名称"></el-input>
        </el-form-item>
        <el-form-item label="盲盒封面" prop="img">
          <el-upload
            class="avatar-uploader"
            action="https://upload-z0.qiniup.com/"
            :data="postData"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="详情页图" prop="details_img">
          <el-upload
            class="avatar-uploader"
            action="https://upload-z0.qiniup.com/"
            :data="postData"
            :show-file-list="false"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="detailUrl" :src="detailUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="分类" prop="class_id">
          <el-select style="width:360px" v-model="form.class_id" placeholder="请选择分类">
            <el-option label="待定" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="盲盒描述">
          <el-input
            type="textarea"
            style="width:360px"
            v-model="form.describe"
            placeholder="请输入盲盒描述"
          ></el-input>
        </el-form-item>-->
        <el-form-item label="流水限制" prop="is_ls">
          <el-input style="width:360px" v-model="form.is_ls" placeholder="输入0为无限制"></el-input>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input style="width:360px" v-model="form.price" placeholder="请输入单价"></el-input>
        </el-form-item>
        <el-form-item label="单箱抽取次数" prop="extract_ci">
          <el-input style="width:360px" v-model="form.extract_ci" placeholder="请输入单箱抽取次数"></el-input>
        </el-form-item>
        <el-form-item label="抽取方式" prop="pattern">
          <el-select style="width:360px" v-model="form.pattern" placeholder="请选择抽取方式">
            <el-option label="单抽" value="1"></el-option>
            <el-option label="不单抽" value="2"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="排序" prop="sort">
          <el-input style="width:360px" v-model="form.sort" placeholder="请输入排序"></el-input>
        </el-form-item>
        <el-form-item label="是否推荐" prop="is_tui">
          <el-select style="width:360px" v-model="form.is_tui" placeholder="请选择是否推荐">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="允许客户抽取次数" prop="allow_ci">
          <el-input style="width:360px" v-model="form.allow_ci" placeholder="请输入单箱允许客户抽取次数0为无限"></el-input>
        </el-form-item>
        <el-form-item label="是否预售" prop="is_ys">
          <el-select style="width:360px" v-model="form.is_ys" placeholder="请选择是否预售">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预售时间" prop="is_ys">
          <el-date-picker
            style="width:360px"
            :disabled="form.is_ys==0"
            v-model="form.ys_time"
            type="datetime"
            placeholder="选择预售时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="是否产生积分" prop="is_integral">
          <el-select style="width:360px" v-model="form.is_integral" placeholder="请选择是否产生积分">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="积分数量" prop="integral">
          <el-input
            style="width:360px"
            :disabled="form.is_integral==0"
            v-model="form.integral"
            placeholder="请输入积分数量"
          ></el-input>
        </el-form-item>

        <el-form-item label="选择奖品" prop="goods_data">
          <el-button size="small" type="primary" round @click="addRewards">添加奖品</el-button>
          <el-table
            :header-cell-style="{background:'#eee'}"
            :data="form.goods_data"
            border
            style="width: 100%;margin-bottom: 20px;"
          >
            <el-table-column type="index" width="50" align="center"></el-table-column>
            <el-table-column align="center" prop="goods_name" label="奖品名称"></el-table-column>
            <el-table-column align="center" label="奖品图片">
              <template slot-scope="scope">
                <el-popover placement="top-start" title trigger="hover">
                  <img :src="scope.row.img" alt style="max-width:150px" />
                  <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
                  <el-avatar
                    slot="reference"
                    shape="square"
                    :size="50"
                    fit="scale-down"
                    :src="scope.row.img"
                  ></el-avatar>
                  <!-- <img
                slot="reference"
                :src="scope.row.img"
                style="width: 60px;height: 60px"
                  />-->
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column align="center" label="中奖名称">
              <template slot-scope="scope">
                <el-select
                  :loading="ruleLoading"
                  @change="choostReward(scope.row)"
                  v-model="scope.row.rule_id"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in ruleoptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" label="数量">
              <template slot-scope="scope">
                <el-input
                  @change="numChange(scope.row)"
                  v-model="scope.row.num"
                  placeholder="请输入数量"
                  :disabled="scope.row.rule_id==''"
                ></el-input>
              </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="测试发数">
              <template slot-scope="scope">
                <el-select v-model="scope.row.is_con" placeholder="请选择是否测试">
                  <el-option label="是" value="1"></el-option>
                  <el-option label="否" value="0"></el-option>
                </el-select>
              </template>
            </el-table-column>-->
            <el-table-column align="center" label="价格" prop="price"></el-table-column>
            <el-table-column align="center" label="成本" prop="y_price"></el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="100">
              <template slot-scope="scope">
                <el-popconfirm
                  confirmButtonText="好的"
                  cancelButtonText="不用了"
                  icon="el-icon-info"
                  iconColor="red"
                  title="这是一段内容确定删除吗？"
                  @onConfirm="handleDel(scope.row)"
                >
                  <el-button slot="reference" type="text" size="small">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="排序" width="160">
              <template slot-scope="scope">
                <el-button @click="goFirst(scope.row)" slot="reference" type="text" size="small">
                  <i class="el-icon-top" style="font-size:25px"></i>
                </el-button>
                <el-button @click="goUp(scope.row)" slot="reference" type="text" size="small">
                  <i class="el-icon-upload2" style="font-size:25px"></i>
                </el-button>
                <el-button @click="goDown(scope.row)" slot="reference" type="text" size="small">
                  <i class="el-icon-download" style="font-size:25px"></i>
                </el-button>
                <el-button @click="goLast(scope.row)" slot="reference" type="text" size="small">
                  <i class="el-icon-bottom" style="font-size:25px"></i>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <div>收入：{{form.income=(form.extract_ci*Number(form.price)).toFixed(2)}}</div>
          <div>实际成本：{{form.cost}} 价格成本：{{form.price_cost}}</div>
          <div>实际利润：{{form.profit=(Number(form.income)-Number(form.cost)).toFixed(2)||'0'}} 价格利润：{{form.price_profit=(Number(form.income)-Number(form.price_cost)).toFixed(2)||'0'}}</div>
          <div>实际利润率：{{form.profit_lv=((Number(form.profit)/Number(form.cost))*100).toFixed(2)||'0'}}% 价格利润率：{{form.price_profit_lv=((Number(form.price_profit )/Number(form.price_cost))*100).toFixed(2)||'0'}}%</div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="WXonSubmit">立即创建</el-button>
          <el-button @click="WXCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-form ref="query" :model="query" label-width="80px">
        <el-form-item label="奖品名称">
          <el-input v-model="query.keywords" placeholder="请输入奖品名称"></el-input>
        </el-form-item>
        <el-form-item label="价格区间">
          <el-input v-model="query.lowPrice" style="width:50px" placeholder="低"></el-input>-
          <el-input v-model="query.heightPrice" style="width:50px" placeholder="高"></el-input>
        </el-form-item>
        <el-form-item label="奖品分类">
          <el-cascader
            @focus="getBoxRewardTypeList"
            v-model="query.class_id"
            :options="queryOptioins"
            :props="{ checkStrictly: true,value:'id',label:'class_name' }"
            placeholder="请选择奖品分类"
            clearable
            :loading="queryLoading"
          ></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryAsk">筛选</el-button>
          <el-button @click="queryReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        @sort-change="sortChange"
        ref="multipleTable"
        :header-cell-style="{background:'#eee'}"
        :data="boxRewardData"
        v-loading="loading"
        border
        style="width: 100%;margin-bottom: 20px;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column align="center" prop="id" label="ID"></el-table-column>
        <el-table-column align="center" prop="goods_name" label="奖品名称"></el-table-column>
        <el-table-column align="center" label="奖品图片">
          <template slot-scope="scope">
            <el-popover placement="top-start" title trigger="hover">
              <img :src="scope.row.img" alt style="max-width:150px" />
              <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
              <el-avatar
                slot="reference"
                shape="square"
                :size="50"
                fit="scale-down"
                :src="scope.row.img"
              ></el-avatar>
              <!-- <img
                slot="reference"
                :src="scope.row.img"
                style="width: 60px;height: 60px"
              />-->
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="class_name" label="分类"></el-table-column>
        <el-table-column align="center" prop="y_price" label="成本"></el-table-column>
        <el-table-column align="center" prop="price" label="价格" sortable="custom"></el-table-column>
        <el-table-column align="center" prop="address" label="预售/现货">
          <template slot-scope="scope">
            <div v-if="scope.row.type==1">预售</div>
            <div v-if="scope.row.type==2">现货</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="address" label="是否参与合成材料">
          <template slot-scope="scope">
            <div v-if="scope.row.is_compound==1">可以</div>
            <div v-if="scope.row.is_compound==0">不可以</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="compound_price" label="合成数值"></el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>

      <div style="margin-top:20px;float:right">
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button @click="subCancel">取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { upload } from '@/api/system'
import { boxRewardList, boxRewardTypeList } from '@/api/boxreward'
import { categoryList } from '@/api/product'
import { addTreasureBox, boxinfo, editTreasureBox } from '@/api/blindbox'
import { rewardList } from '@/api/system'
import { parseTime } from '@/utils/index'

export default {
  name: 'AddTreasureHunt',
  data() {
    return {
      title: '添加',
      formLoading: false,
      // 分页数据
      total: 0,
      currentPage: 1,
      pageSize: 10,
      //query
      query: {
        keywords: '',
        class_id: '0',
        lowPrice: '',
        heightPrice: '',
        order_by: ''
      },
      boxRewardData: [],
      form: {
        name: '',
        img: '',
        details_img: '',
        class_id: '0',
        describe: '',
        is_ls: '',
        price: '',
        pattern: '',
        sort: '',
        is_tui: '',
        is_ys: '',
        ys_time: '',
        is_integral: '',
        integral: '0',
        goods_data: [],
        income: '',
        cost: '',
        profit: '',
        profit_lv: '',
        extract_ci: '',
        allow_ci: ''
      },
      rules: {
        name: [{ required: true, message: '请输入盲盒名称', trigger: 'blur' }],
        img: [{ required: true, message: '请上传封面图片', trigger: 'blur' }],
        details_img: [
          { required: true, message: '请上传详情图片', trigger: 'blur' }
        ],
        class_id: [{ required: true, message: '请选择分类', trigger: 'blur' }],
        price: [{ required: true, message: '请输入奖单价', trigger: 'blur' }],
        extract_ci: [
          { required: true, message: '请输入单箱抽取次数', trigger: 'blur' }
        ],
        is_ls: [{ required: true, message: '请输入流水限制', trigger: 'blur' }],
        allow_ci: [
          { required: true, message: '请输入用户允许抽取次数', trigger: 'blur' }
        ],
        pattern: [
          { required: true, message: '请选择抽取方式', trigger: 'blur' }
        ],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        is_tui: [
          { required: true, message: '请选择是否推荐', trigger: 'blur' }
        ],
        is_cc: [
          { required: true, message: '请选择是否存在冲冲赏', trigger: 'blur' }
        ],
        is_integral: [
          { required: true, message: '请输选择是否产生积分', trigger: 'blur' }
        ],
        integral: [
          { required: true, message: '请输入积分数量', trigger: 'blur' }
        ],
        goods_data: [{ required: true, message: '请选择奖品', trigger: 'blur' }]
      },
      // 上传图片
      url: '',
      imageUrl: '',
      postData: {
        token: ''
      },
      detailUrl: '',
      // 编辑抽屉
      drawer: false,
      direction: 'rtl',
      title: '奖品',
      loading: false,
      priceArr: [],
      queryLoading: false,
      queryOptioins: [],
      //添加奖品列表
      selectArr: [],
      ruleoptions: [],
      ruleLoading: false,
      totalnum: 0,
      classId: '0'
    }
  },
  mounted() {
    this.form.ys_time = new Date()
    this.title = this.$route.query.title
    if (this.title == '添加') {
      this.getrule()
    }
    this.getToken()
    if (this.title == '编辑') {
      this.getTXinfo()
    }
  },
  activated() {
    this.form.ys_time = new Date()
    this.title = this.$route.query.title
    if (this.title == '添加') {
      this.getrule()
    }
    this.getToken()
    if (this.title == '编辑') {
      this.getTXinfo()
    }
  },
  methods: {
    // 获取详细信息
    async getTXinfo() {
      await this.getrule()
      this.formLoading = true
      const res = await boxinfo({ id: this.$route.query.id })
      this.formLoading = false
      console.log(res)
      this.form = res.data
      this.imageUrl = res.data.img
      this.detailUrl = res.data.details_img
      this.totalnum = res.data.extract_ci
    },
    // 去除小数最后的0
    removeTrailingZeros(num) {
      const str = num.toString()
      return str.indexOf('.') !== -1 ? str.replace(/\.?0*$/, '') : str
    },
    WXonSubmit() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          if (this.form.is_ys == 0) {
            this.form.ys_time = 0
          } else {
            this.form.ys_time = parseTime(this.form.ys_time)
          }
          // 检查表中数据有无漏填
          for (let i = 0; i < this.form.goods_data.length; i++) {
            if (
              !this.form.goods_data[i].rule_id ||
              this.form.goods_data[i].num == 0
            ) {
              this.$message.error('请确认是否选择中奖名称或是否填写奖品数量！')
              return
            } else if (this.form.is_integral == 1) {
              if (this.form.integral == 0) {
                this.$message.error('产生积分积分不能为0！')
                return
              }
            } else if (this.form.goods_data[i].win_type == 0) {
              if (this.totalnum != this.form.extract_ci) {
                this.$message.error(
                  '请确认购买可得总数跟单项抽取次数是否相等！'
                )
                return
              }
            } else if (this.totalnum == 0) {
              this.$message.error('请选择一个购买可得的奖品！')
              return
            }
          }
          if (this.title == '添加') {
            const res = await addTreasureBox({ ...this.form })
            if (res.st == 1) {
              this.$message({
                message: '添加成功',
                type: 'success'
              })

              // 调用全局挂载的方法,关闭当前标签页
              this.$store.dispatch('tagsView/delView', this.$route)
              //返回上一个tab页面 返回上一步路由，
              this.$router.go(-1)
            } else {
              console.log(res)
              this.$message.error(res.msg)
            }
          } else if (this.title == '编辑') {
            const res = await editTreasureBox({ ...this.form })
            if (res.st == 1) {
              this.$message({
                message: '编辑成功',
                type: 'success'
              })

              // 调用全局挂载的方法,关闭当前标签页
              this.$store.dispatch('tagsView/delView', this.$route)
              //返回上一个tab页面 返回上一步路由，
              this.$router.go(-1)
            } else {
              console.log(res)
              this.$message.error(res.msg)
            }
          }
        }
      })
    },
    WXCancel() {
      // 调用全局挂载的方法,关闭当前标签页
      this.$store.dispatch('tagsView/delView', this.$route)
      //返回上一个tab页面 返回上一步路由，
      this.$router.go(-1)
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.imageUrl = this.url + res.key
      this.form.img = this.imageUrl
    },
    beforeAvatarUpload(file) {
      //   const isJPG = file.type === "image/jpeg";
      //   if (!isJPG) {
      //     this.$message.error("上传头像图片只能是 JPG 格式!");
      //   }
      const isLt1M = file.size / 1024 / 1024 < 1

      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!')
        return
      }
    },
    handleSuccess(res, file) {
      this.detailUrl = this.url + res.key
      this.form.details_img = this.detailUrl
    },
    beforeUpload(file) {
      //   const isJPG = file.type === "image/jpeg";
      //   if (!isJPG) {
      //     this.$message.error("上传头像图片只能是 JPG 格式!");
      //   }
      const isLt1M = file.size / 1024 / 1024 < 1

      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!')
        return
      }
    },
    async getToken() {
      const res = await upload()
      this.postData.token = res.data.uptoken
      this.url = res.data.domain
    },
    //抽屉
    handleClose(done) {
      this.drawer = false
      done()
    },
    subCancel() {
      this.drawer = false
    },
    //分页改变
    async currentChange(current) {
      this.currentPage = current
      await this.getBoxRewardList()
      const select = []
      console.log(this.form.goods_data)
      if (this.form.goods_data) {
        this.form.goods_data.forEach((good) => {
          this.boxRewardData.forEach((item) => {
            if (good.goods_id == item.id) {
              select.push(item)
            }
          })
        })
      }
      this.toggleSelection(select)
    },
    // 添加奖品
    async addRewards() {
      this.drawer = true
      await this.getBoxRewardList()
      const select = []
      console.log(this.form.goods_data)
      if (this.form.goods_data) {
        this.form.goods_data.forEach((good) => {
          this.boxRewardData.forEach((item) => {
            if (good.goods_id == item.id) {
              select.push(item)
            }
          })
        })
      }
      this.toggleSelection(select)
      this.selectArr = this.form.goods_data
    },
    //获取奖品列表
    async getBoxRewardList() {
      this.loading = true
      const res = await boxRewardList({
        page: this.currentPage,
        limit: this.pageSize,
        class_id: this.classId,
        price: this.priceArr,
        keywords: this.query.keywords,
        order_by: this.query.order_by
      })
      this.loading = false
      console.log(res)
      this.total = res.count
      this.boxRewardData = res.data
    },
    //获取奖品分类列表
    async getBoxRewardTypeList() {
      this.queryLoading = true
      const res = await categoryList({
        page: '1',
        limit: '999',
        keywords: ''
      })
      this.queryLoading = false
      console.log(res)
      this.queryOptioins = res.data
    },
    // 搜索列表
    queryAsk() {
      // 不可以一个有值一个没值
      if (!this.query.lowPrice && !this.query.heightPrice) {
        console.log(this.query)
        this.priceArr = []
        this.classId = this.query.class_id[this.query.class_id.length - 1]
        this.currentPage = 1
        this.getBoxRewardList()
      } else if (this.query.lowPrice && this.query.heightPrice) {
        this.priceArr = [this.query.lowPrice, this.query.heightPrice]
        console.log(this.query)
        this.classId = this.query.class_id[this.query.class_id.length - 1]
        this.currentPage = 1
        this.getBoxRewardList()
      } else if (!this.query.lowPrice || !this.query.heightPrice) {
        this.$message.error('请输入价格区间')
      }
    },
    queryReset() {
      this.resetForm('query')
      this.total = 0
      this.currentPage = 1
      this.pageSize = 10
      this.query.keywords = ''
      this.query.type = '0'
      this.query.lowPrice = ''
      this.query.heightPrice = ''
      this.query.order_by = ''
      this.query.class_id = '0'
      this.classId = '0'
      this.getBoxRewardList()
    },
    // 选择奖品

    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },

    handleSelectionChange(val) {
      this.selectArr = []
      //已经有的不添加
      const aIds = new Set(this.selectArr.map((item) => item.id))
      val.forEach((item) => {
        if (!aIds.has(item.id)) {
          this.selectArr.push(item)
        }
      })
    },
    onSubmit() {
      console.log(this.form.goods_data)
      const aIds = new Set(this.form.goods_data.map((item) => item.goods_id))
      this.selectArr.forEach((item) => {
        if (!aIds.has(item.id)) {
          const dx = {
            goods_id: item.id,
            rule_id: '',
            sort: '',
            num: '0',
            win_type: '-1',
            img: item.img,
            goods_name: item.goods_name,
            price: item.price,
            y_price: item.y_price,
            id: '0'
          }
          this.form.goods_data.unshift(dx)
        }
      })
      this.form.goods_data.sort((a, b) => b.price - a.price)
      this.form.goods_data.forEach((item, index) => {
        console.log(index)
        item.sort = this.form.goods_data.length - (index + 1)
      })
      console.log(this.form.goods_data)
      // this.selectArr.forEach(item => {
      //   if (!aIds.has(item.id)) {
      //     const dx = {
      //       goods_id: item.id,
      //       rule_id: "",
      //       sort: "",
      //       num: "0",
      //       con_start: "0",
      //       con_end: "0",
      //       img: item.img,
      //       goods_name: item.goods_name,
      //       price: item.price,
      //       y_price: item.y_price,
      //       is_con: "0",
      //       id: "0"
      //     };
      //     if (this.form.goods_data.length == 0) {
      //       dx.sort = 0;
      //     } else {
      //       console.log(this.form.goods_data[0].sort);
      //       dx.sort = Number(this.form.goods_data[0].sort) + 1;
      //     }
      //     this.form.goods_data.unshift(dx);
      //   }
      // });
      // console.log(this.form.goods_data);
      this.drawer = false
    },
    async getrule() {
      this.ruleLoading = true
      const res = await rewardList({
        page: '1',
        limit: '999',
        keywords: '',
        type: '3'
      })
      this.ruleoptions = res.data
      this.ruleLoading = false
    },
    //选择中将名称判断
    choostReward(row) {
      this.ruleoptions.forEach((item) => {
        if (item.id == row.rule_id) {
          this.form.goods_data.forEach((good) => {
            if (good.goods_id == row.goods_id) {
              this.ruleoptions.forEach((item) => {
                // 找到赏级的数据
                if (item.id == row.rule_id) {
                  // 判断出奖类型
                  if (item.obtain == 1) {
                    good.win_type = 0
                  } else if (item.obtain == 2) {
                    if (item.scene == 0 || item.scene == 1) {
                      good.win_type = 1
                    } else if (item.scene == 2) {
                      good.win_type = 2
                    }
                  }
                }
              })
            }
          })
        }
      })
    },
    // 数量改变
    numChange(row) {
      console.log(row)
      if (Number(row.num) != Math.floor(row.num)) {
        this.$message.error('奖品数量为整数')
        return
      }
      if (Number(row.num) <= 0) {
        this.$message.error('奖品数量需大于0')
        return
      }

      this.form.cost = 0
      this.form.price_cost = 0
      this.totalnum = 0
      if (this.form.goods_data) {
        this.form.goods_data.forEach((item) => {
          // 成本
          let cost = Number((item.num * item.y_price).toFixed(2))
          this.form.cost = Number((this.form.cost += cost).toFixed(2))
          // 价格
          let price_cost = Number((item.num * item.price).toFixed(2))
          this.form.price_cost = Number(
            (this.form.price_cost += price_cost).toFixed(2)
          )
          if (item.win_type == 0) {
            this.totalnum += Number(item.num)
          }
        })
      }
      console.log(this.totalnum)
    },
    handleDel(row) {
      this.form.goods_data.forEach((good, index) => {
        if (good.goods_id == row.goods_id) {
          this.form.goods_data.splice(index, 1)
        }
      })
    },
    // 图表排序
    goFirst(row) {
      row.sort = this.form.goods_data[0].sort
      let index = this.form.goods_data.indexOf(row)
      let item = this.form.goods_data.splice(index, 1)[0] // 从数组中移除该项并获得它
      this.form.goods_data.unshift(item) // 将该项插入到数组的开头
      for (let i = 0; i < this.form.goods_data.length; i++) {
        this.form.goods_data[i].sort = this.form.goods_data[0].sort - i
      }
    },
    goUp(row) {
      let index = this.form.goods_data.indexOf(row)

      if (index > 0) {
        this.form.goods_data.splice(
          index - 1,
          0,
          this.form.goods_data.splice(index, 1)[0]
        )
      }
      let j = this.form.goods_data.length - 1
      for (let i = 0; i < this.form.goods_data.length; i++) {
        this.form.goods_data[i].sort = j
        j--
      }
    },
    goDown(row) {
      let index = this.form.goods_data.indexOf(row)
      if (index < this.form.goods_data.length - 1) {
        this.form.goods_data.splice(
          index + 1,
          0,
          this.form.goods_data.splice(index, 1)[0]
        )
      }
      let j = this.form.goods_data.length - 1
      for (let i = 0; i < this.form.goods_data.length; i++) {
        this.form.goods_data[i].sort = j
        j--
      }
    },
    goLast(row) {
      row.sort = this.form.goods_data[this.form.goods_data.length - 1].sort
      let index = this.form.goods_data.indexOf(row)
      let item = this.form.goods_data.splice(index, 1)[0] // 从数组中移除该项并获得它
      this.form.goods_data.push(item) // 将该项插入到数组的末尾
      let j = this.form.goods_data.length - 1
      for (let i = 0; i < this.form.goods_data.length; i++) {
        this.form.goods_data[i].sort = j
        j--
      }
    },
    // 排序
    sortChange({ column, prop, order }) {
      if (order == 'descending') {
        this.query.order_by = prop + ',' + 'desc'
        this.getBoxRewardList()
      } else if (order == 'ascending') {
        this.query.order_by = prop + ',' + 'asc'
        this.getBoxRewardList()
      }
    },

    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}
.clearfix:after {
  clear: both;
}
.search {
  display: flex;
  align-items: center;
}
::v-deep .el-drawer.rtl {
  width: 650px !important;
  overflow: auto;
  .el-form {
    display: flex;
    flex-wrap: wrap;
  }
}
::v-deep .el-textarea__inner {
  width: 360px !important;
}
::v-deep .el-drawer.rtl {
  padding-bottom: 20px;
  width: 800px !important;
  overflow: auto;
}
// 上传图片
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>